{% extends 'base.html' %}
{% load thumbnail %}

{% block title %}
    {{ image.title }}
{% endblock %}

{% block content %}
    <h1>{{ image.title }}</h1>

    {% thumbnail image.image "300" as im %}
        <a href="{{ image.image.url }}">
            <img src="{{ im.url }}" class="image-detail">
        </a>
    {% endthumbnail %}

    {% with total_likes=image.users_like.count users_like=image.users_like.all %}
        <div class="image-info">
            <div>
            <span class="count">
                 <span class="total">{{ total_likes }}</span>
                 like{{ total_likes|pluralize }}
            </span>
            <span class="count">
            {{ total_views }} view{{ total_views|pluralize }}
            </span>
                <a href="#" data-id="{{ image.id }}" data-action="{% if request.user in users_like %}un{% endif %}like"
                   class="like button">
                    {% if request.user not in users_like %}
                        Like
                    {% else %}
                        Unlike
                    {% endif %}
                </a>
            </div>
            {{ image.desc|linebreaks }}
        </div>

        <div class="image-likes">
            {% for user in image.users_like.all %}
                <div>
                    <img src="{{ user.profile.photo.url }}">
                    <p>{{ user.first_name }}</p>
                </div>
            {% empty %}
                Nobody likes this image yet.
            {% endfor %}
        </div>
    {% endwith %}
{% endblock %}

{% block domready %}
    $('a.like').click(function (e) {
    e.preventDefault();
    $.post('{% url 'images:like' %}',
    {
    id: $(this).data('id'),
    action: $(this).data('action'),
    },
    function (data) {
    if (data['status'] === 'ok') {
    let previous_action = $('a.like').data('action');
    //切换 data-action 属性
    $('a.like').data('action', previous_action === 'like' ? 'unlike' : 'like');
    //切换按钮文本
    $('a.like').text(previous_action === 'like' ? 'unlike' : 'like');
    //更新总的喜欢人数
    let previous_likes = parseInt($('span.count.total').text());
    $('span.count.total').text(previous_action === 'like' ? previous_likes + 1 : previous_likes - 1);
    }
    }
    );
    });
{% endblock %}